package com.cyy.util

import java.util.*
import java.util.regex.Pattern

class TreeBuilder constructor(val properties: Properties, val useNumericKeysAsArrayIndexes: Boolean = true) {
    constructor(properties: Properties) : this(properties, true) {
    }

    private val pattern = Pattern.compile("[0-9]+")
    val m = mutableMapOf<List<String>, Any>()
    fun build(): PropertyTree {
        val root = PropertyTree()
        //jdk 1.8 stream opt
        properties.stringPropertyNames().map {
            m.put(splitPropertyName(it), ValueConverter.asObject(properties.getProperty(it)))
        }
        m.forEach { (keyPath, value) -> root.appendBranchFromKeyValue(keyPath, value) }
        return root
    }


    private fun splitPropertyName(property: String): List<String> {
        val strings = property.split("\\.")
        val result = if (useNumericKeysAsArrayIndexes) applyArrayNotation(strings) else strings
        Collections.reverse(result)
        return result
    }

    private fun applyArrayNotation(strings: List<String>): List<String> {
        val result = ArrayList<String>()
        for (element in strings) {
            val matcher = pattern.matcher(element)
            if (matcher.matches()) {
                val index = result.size - 1
                result[index] = result[index] + String.format("[%s]", element)
            } else {
                result.add(element)
            }
        }
        return result
    }
}